package com.ww.demo.thread.d3;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockConditionDemo {
    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();

    public static void main(String[] args) {
        LockConditionDemo demo = new LockConditionDemo();
//        new Thread(() -> demo.await(), "thread1").start();
//        try {
//            Thread.sleep(3000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//        new Thread(() -> demo.signal(), "thread2").start();


        new Thread(() -> demo.await(demo.condition2), "thread3").start();
        new Thread(() -> demo.await(demo.condition3), "thread4").start();
        new Thread(() -> demo.signal(demo.condition2), "thread3").start();
        System.out.println("等待5秒再通知线程4");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> demo.signal(demo.condition3), "thread4").start();
        System.out.println(demo.lock.isFair());
    }

    private void await(Condition condition){
        lock.lock();
        System.out.println("开始等待await1 ThreadName:" + Thread.currentThread().getName());
        try {
            condition.await();
            System.out.println("等待await结束! ThreadName:" + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    private void signal(Condition condition){
        lock.lock();
        System.out.println("发送通知signal! ThreadName: " + Thread.currentThread().getName());
        condition.signal();
        lock.unlock();
    }

    private void await(){
        lock.lock();
        System.out.println("开始等待await! ThreadName:" + Thread.currentThread().getName());
        try {
            condition.await();
            System.out.println("等待await结束,ThreadName:" + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    private void signal(){
        lock.lock();
        System.out.println("发送通知signal! ThreadName:" + Thread.currentThread().getName());
        condition.signal();
        lock.unlock();
    }
}
